<template>
  <van-loading v-if="loading" vertical>
    <template #icon>
      <van-icon name="star-o" size="30" />
    </template>
    加载中...
  </van-loading>
  <van-notice-bar
    v-if="showMessage"
    scrollable
    left-icon="volume-o"
    color="#1989fa"
    background="#ecf9ff"
    :text="`通知:本站验证码功能尚未联网,不再通过手机发送,以下是你的验证码:${codeMessage}`"
  />
  <van-form style="margin-top: 100px" @submit="onSubmit">
    <van-cell-group v-if="codeOrPassword === 0" inset>
      <van-field
        clearable
        v-model="phone"
        label="手机号"
        placeholder="请输入手机号"
        :rules="[{ validator: validatorMessagePhone }]"
        ><template #button>
          <van-button
            v-if="!showButton"
            size="small"
            type="primary"
            @click="sendCode"
            >发送验证码</van-button
          >
          <van-button
            v-if="showButton"
            size="small"
            loading
            type="primary"
            :loading-text="codeBtnMsg"
          /> </template
      ></van-field>
      <van-field
        clearable
        v-model="code"
        label="验证码"
        placeholder="请输入验证码"
        style="margin-top: 20px"
        :rules="[{ validator: validatorMessageCode }]"
      />
    </van-cell-group>
    <van-cell-group v-if="codeOrPassword === 1" inset>
      <van-field
        v-model="phone"
        label="账号"
        placeholder="请输入账号"
        :rules="[{ validator: validatorMessagePhone }]"
      />
      <van-field
        clearable
        v-model="userPassword"
        type="password"
        label="密码"
        placeholder="请输入密码"
        style="margin-top: 20px"
        :rules="[{ validator: validatorMessagePassword }]"
      />
    </van-cell-group>

    <div class="login-radio">
      <div>
        <van-radio />
      </div>
      <div>
        我已阅读并同意
        <a href="javascript:void(0)" @click="dialog">《用户须知》</a>和<a
          href="javascript:void(0)"
          @click="showCenter = true"
          >《PC端须知》</a
        >
      </div>
    </div>
    <!-- <img :src="`${imgCodeUrl}`" id="imgCode" @click="refreshCode" /> -->
    <van-button class="buttonForLogin" type="primary" native-type="submit"
      >登录</van-button
    ></van-form
  >
  <van-popup v-model:show="showCenter" round :style="{ padding: '64px' }">
    由于本作品是移动端APP,如果你是PC端,请做出如下操作以切换至移动端访问:<br />1、按下键盘上的F12<br />2、同时按下Ctrl+Shift+M
  </van-popup>
  <van-space :size="0" style="padding: 140px 0 0 95px">
    <div>
      <van-icon
        name="add-o"
        size="40"
        @click="toRegister"
        class="buttonForReg"
      /><van-cell style="font-size: 15px">注册</van-cell>
    </div>
    <div v-if="codeOrPassword === 0" style="margin-left: 50px">
      <van-icon
        name="user-circle-o
"
        size="40"
        @click="codeOrPassword = 1"
        class="buttonForPassword"
      /><van-cell style="font-size: 15px">密码登录</van-cell>
    </div>
    <div v-if="codeOrPassword === 1" style="margin-left: 50px">
      <van-icon
        name="user-circle-o
"
        size="40"
        @click="codeOrPassword = 0"
        class="buttonForPassword"
      /><van-cell style="font-size: 15px">验证码登录</van-cell>
    </div>
  </van-space>
</template>

<script setup lang="ts">
import myAxios from "../plugins/myAxios";
import { ref } from "vue";
import { useRouter } from "vue-router";
import { showSuccessToast, showFailToast, showDialog } from "vant";

const isDev = process.env.NODE_ENV === "development";
let imgCodeUrl = isDev
  ? "http://127.0.0.1:8081/api/user/getImgCode"
  : "https://gouhuo-backend.allbugs.top/api/user/getImgCode";
const refreshCode = () => {
  document.getElementById("imgCode").src =
    `${imgCodeUrl}` + "?" + new Date().getTime();
};

const loading = ref(false);
//发送验证码
const phone = ref(""); //手机号
const code = ref(""); //验证码
const showButton = ref(false); //展示验证码加载的按钮
let codeBtnMsg = ref(""); //验证码加载文案
const showMessage = ref(false); //展示顶部消息
const codeMessage = ref(""); //后端返回的验证码-用作展示给用户
const sendCode = async () => {
  if (phone.value.trim() == "" || !isPhone.value) {
    return;
  }
  const res = await myAxios.post("/user/code?phone=" + phone.value);
  if (res.code === 0) {
    codeMessage.value = res.message;
    showMessage.value = true;
  }
  showButton.value = true;
  // 按钮倒计时
  let i = 60;
  codeBtnMsg.value = i-- + "秒后重发";
  let taskId = setInterval(() => (codeBtnMsg.value = i-- + "秒后重发"), 1000);
  setTimeout(() => {
    showButton.value = false;
    clearInterval(taskId);
  }, 59000);
};

const showCenter = ref(false); //展示<<PC端须知>>
const dialog = () => {
  showDialog({
    title: "欢迎来到篝火1.0.0 ",
    message:
      "正如你所见,目前产品还处于前期测试阶段,页面效果、逻辑运行和功能体现都不尽人意,但它已是我竭尽所能的作品。\n本作品前端基于Vue3+Vant4、后端基于SpringBoot+Mybatis_Plus+Redis,仅供学习交流用;\r限于个人能力和服务器性能,使用过程中可能会有这样那样的延迟和bug,如果你不幸遇到,可以通过个人页面的反馈功能向我告知,我也会在后续的版本迭代中不断优化。谢谢你的配合与理解",
    theme: "round-button",
  }).then(() => {});
};

const special = /[-!$%^&*()_+|~=`{}\[\]:";'<>?,.\/]/; //匹配特殊字符的正则
const isPhone = ref(false); //匹配手机号的正则
const validatorMessagePhone = (val: string) => {
  isPhone.value = false;
  if (val.trim() == "") {
    return "手机号不能为空";
  }
  if (special.test(val)) {
    return "手机号不能包含特殊字符";
  }
  const check = /^1[3-9]\d{9}$/;
  if (!check.test(val)) {
    return "手机号格式错误";
  }
  isPhone.value = true;
};
const validatorMessageCode = (val: string) => {
  if (val.trim() == "") {
    return "验证码不能为空";
  }
  if (val.length != 4) {
    return "验证码长度为4位!";
  }
  if (special.test(val)) {
    return "验证码不能包含特殊字符";
  }
};
const validatorMessagePassword = (val: string) => {
  if (val.trim() == "") {
    return "密码不能为空";
  }
  if (val.length < 8 || val.length > 16) {
    return "密码长度必须在8-16位之间";
  }
  if (!val.match(/^(?=.*[0-9])(?=.*[a-zA-Z])([a-zA-Z0-9]+)$/)) {
    return "密码必须只包含数字和字母";
  }
  if (special.test(val)) {
    return "密码不能包含特殊字符";
  }
};

// 跳转到注册页
const router = useRouter();
const toRegister = () => {
  router.push({
    path: "/user/reg",
  });
};

const codeOrPassword = ref(0); //选择的是验证码或密码登录
const userPassword = ref(""); //密码
const onSubmit = async () => {
  let response;
  loading.value = true;
  const res = await myAxios.post(
    "/user/login",
    codeOrPassword.value === 0
      ? {
          phone: phone.value,
          userCode: code.value,
          remember: 1,
        }
      : {
          phone: phone.value,
          userPassword: userPassword.value,
          remember: 1,
        }
  );
  response = res;
  if (response.code === 0 && response.data) {
    // 跳转到之前的页面
    const redirectUrl = isDev
      ? window.location.href.split("3")[2] ?? "/"
      : window.location.href.split("1")[2] ?? "/";
    router.push({
      path: redirectUrl,
      replace: true,
    });
    showSuccessToast("小智暖心提醒:登录成功");
  } else {
    showFailToast(`小智遗憾告知:${response.message}`);
  }
  loading.value = false;
};
</script>

<style scoped>
@import "../assets/css/login.css";
</style>
